from tornado.websocket import WebSocketHandler
from tornado.web import RequestHandler

from cache import sockets
from service import *


class GameHandler(RequestHandler):

    services = {
        'sign-in': sign_in,
        'sign-up': sign_up,
        'sign-out': sign_out,
        'reset-password': reset_password,
        'set-ready': set_ready,
        'change-partner': change_partner,
        'new-step': new_step,
        'retract-ask': retract_ask,
        'retract-answer': retract_answer,
        'resign': resign
    }

    def post(self):
        action = self.get_argument('action')
        service = self.services.get(action)
        if service is None:
            response = {'result': 'ERROR_SERVICE_NOT_FOUND'}
            self.write(response)
            return
        args = self.request.arguments
        for key in args:
            if isinstance(args[key], list):
                args[key] = args[key][0]
        response = service(args)
        response['action'] = action
        self.write(response)


class PushHandler(WebSocketHandler):

    connected = False
    username = None

    def check_origin(self, origin):
        return True

    def allow_draft76(self):
        return True

    def open(self):
        print('connect receive')

    def on_message(self, message):
        request = json.loads(message)
        username = request['username']
        token = request['token']
        self.username = username
        if token == cache.cache_session.online_users.get(username)[1]:
            # authenticated
            sockets[username] = self
            response = json.dumps({'result': 'ok', 'action': 'sign-in'})
            self.write_message(response)
            push.push_first_partner(username)
        else:
            response = json.dumps({'result': 'ERROR_USER_UNAUTHORIZED'})
            self.write_message(response)

    def on_close(self):
        cache.force_offline(self.username)

    def close(self, code=None, reason=None):
        self.connected = False
        super(PushHandler, self).close()
        sockets.pop(self.username)


class EchoHandler(WebSocketHandler):

    def allow_draft76(self):
        return True

    def check_origin(self, origin):
        return True

    def open(self):
        print "new client opened"

    def on_close(self):
        print "client closed"

    def on_message(self, message):
        self.write_message(message)


class IndexHandler(RequestHandler):
    def get(self):
        self.redirect('/static/index.html')
